<template>
  <view class="page">
    <my-modal ref="modal" title="套餐配送" width="92%" :top="navBarHeight" @clickModal="clickModal()" @clickBtn="clickBtn()" @afterModalClose="afterModalClose()" zIndex="9999">
      <view class="modal-container">
        <!-- 套餐数据 -->
        <view class="meal-container">
          <view class="width-50 text-ellipsis">{{ meal.name }}</view>
          <NumberBox :value="meal.selectNumber" :min="meetSelectNumber" :minHiddenMinus="true" :rowData="meal" @change="mealGoodsChange"></NumberBox>
        </view>

        <swiper class="goods-swiper" :current="currentSwiperIndex" @change="swiperChange">
          <swiper-item v-for="(mealForm, index) in selectMealForm" :key="mealForm.setsubname" class="goods-swiper-item">
            <scroll-view scroll-y scroll-with-animation class="goods-container">
              <view class="swiper-title"> {{ mealForm.setsubname }}配送 </view>
              <view v-for="item in mealFormGoods[index]" :key="item.setinfoid" class="goods-item">
                <view class="is-flex justify-between items-center">
                  <view class="goods-name">{{ item.goodsname }}</view>
                  <view v-if="!item.hiddenHandle" class="color-gold" @click="setMaxNumber(item, mealFormGoods[index])">最多</view>
                </view>

                <view class="tags">
                  <tui-tag v-if="$utils.isNumber(item.isgive)" type="gold" margin="0 4px 0 0" padding="3px 4px" size="9px" plain>
                    {{ item.isgive | isGiveType }}
                  </tui-tag>
                  <tui-tag v-if="item.number >= 0" type="gold" margin="0 4px 0 0" padding="3px 4px" size="9px" plain>
                    {{ mealFormGoods[index].length === 1 ? '固送' : '可选' }} {{ item.number }}
                  </tui-tag>
                </view>

                <view class="is-flex justify-between items-center">
                  <view class="is-flex items-center color-gold">
                    <view class="text-price font-weight-bold">{{ item.goodsprice }}</view>
                    <!-- <view class="fs-xs ml-5">{{ item.goodsunit }}</view> -->
                  </view>

                  <NumberBox
                    :value="item.selectNumber"
                    :rowData="item"
                    :max="item.number"
                    :hiddenHandle="item.hiddenHandle"
                    @addChange="goodsChange(item, item.selectNumber + 1, mealFormGoods[index], 'plus')"
                    @lessChange="goodsChange(item, item.selectNumber - 1, mealFormGoods[index], 'minus')"
                  ></NumberBox>
                </view>
              </view>
            </scroll-view>
          </swiper-item>
        </swiper>

        <view class="button-box">
          <button v-if="ifShowPreButton" class="my-button pre-button" @click="handlePre()">上一步</button>
          <button v-if="ifShowNextButton" class="my-button next-button" @click="handleNext()">下一步</button>
          <button v-if="ifShowSubmitButton" class="my-button submit-button" @click="handleSubmit()">确定</button>
        </view>
      </view>
    </my-modal>
  </view>
</template>

<script>
import NumberBox from '@/pages/shop/components/number-box/number-box.vue'
import common from '@/pages/shop/mixins/common'
export default {
  name: 'ModalMealForm',
  components: { NumberBox },
  mixins: [common],
  props: {
    modalButtons: {
      type: Array,
      default: () => {
        return [{ text: '确认选中', type: 'gold', plain: false, handle: 'addToCart' }]
      }
    },
    // 选中的套餐
    selectMeal: {
      props: Object,
      default: null
    },
    selectMealForm: {
      props: Array,
      default: null
    },
    selectMealFormGroups: {
      props: Array,
      default: null
    },
    selectMealFormGoods: {
      props: Array,
      default: null
    }
  },
  data() {
    return {
      // 是否需要主动调用 addGoodsChange 才能将选中数据添加到缓存中
      ifManualAdd: false,

      currentSwiperIndex: 0
    }
  },
  computed: {
    // 选中的主套餐
    meal() {
      // if (this.selectMeal) this.selectMeal.Lscs = '20201' // 测试模拟
      return this.selectMeal || {}
    },

    // 最低需要选择的主套餐数 // 默认 1 件起
    meetSelectNumber() {
      const lscs = this.$format(this.meal, 'Lscs', '')
      return this.getLscs(lscs, '满') || 1
    },

    // 例送数量
    lsNumber() {
      return this.getLscsNumber(this.meal.selectNumber, this.$format(this.meal, 'Lscs', ''))
    },

    // 选中的套餐详情 - 分组商品
    mealFormGoods() {
      return this.selectMealFormGoods
    },

    // 上一步按钮
    ifShowPreButton() {
      // 第一条数据不限时
      if (this.currentSwiperIndex === 0) return false
      return true
    },

    // 下一步按钮
    ifShowNextButton() {
      if (!this.mealFormGoods) return false

      // 无数据不显示
      if (this.mealFormGoods.length === 0) return false

      // 最后一条不显示
      if (this.currentSwiperIndex === this.mealFormGoods.length - 1) return false

      return true
    },

    // 确认提交按钮
    ifShowSubmitButton() {
      if (!this.mealFormGoods) return false

      // 无数据显示
      if (this.mealFormGoods.length === 0) return true

      // 最后一条显示
      if (this.currentSwiperIndex === this.mealFormGoods.length - 1) return true

      return false
    }
  },
  filters: {
    // 收费 / 赠送
    isGiveType(val) {
      const dict = { 0: '收费', 1: '赠送' }
      return dict[val] || ''
    },
    // 是否可选 (0:否、1:是)
    isSelect(val) {
      return val === 1 ? '可选' : ''
    }
  },
  methods: {
    init() {
      // 进入默认选中主套餐  (满 meetSelectNumber 多少件起 ) meetSelectNumber 件
      if (this.meal) {
        this.$set(this.meal, 'selectNumber', this.meetSelectNumber)

        // 确保拿到更新后的数据
        setTimeout(() => {
          this.mealGoodsChange(this.meetSelectNumber, null, 'plus')
          return
        })
      }
    },

    /**
     * 主套餐进行选择
     */
    mealGoodsChange(selectNumber) {
      selectNumber = Number(selectNumber)
      this.meal.selectNumber = selectNumber // 为了更新到 this.meal.selectNumber

      // this.$msg('text', '修改主套餐数量需重新选择各组配送数量哦 ～')
      this.refreshMealFormGoodsNumber(this.meal.selectNumber)

      this.currentSwiperIndex = 0 // 重新修改回 A 组配送
    },

    /**
     * 更新商品分组内的商品可选数
     * 且对套餐内单条数据即固送商品进行特殊处理
     */
    refreshMealFormGoodsNumber(mealSelectNumber) {
      this.mealFormGoods.forEach(goods => {
        goods.forEach(item => {
          // 随主套餐数量修改更新可选数量
          this.$set(item, 'number', item.singleNumber * (mealSelectNumber + this.lsNumber))

          // 如果套餐组内只有一条数据，证明是固收。修改主套餐数量的时候直接给他更新的可选数量最大值
          if (goods.length === 1) {
            item.selectNumber = item.number
            item.hiddenHandle = true
          } else {
            // 如果有多条数据，证明套餐组内为多个可选。重置所有已选数量
            item.selectNumber = 0
          }
        })
      })
    },

    async addToCart() {
      const ifAddToCart = await this.computedIfFullSelect()

      if (!ifAddToCart) return

      const mealFormGoods = [].concat.apply([], this.mealFormGoods)

      // 过滤有选中的商品添加到子套餐的信息中
      const hasSelectGoods = mealFormGoods.filter(goodItem => {
        return goodItem.selectNumber > 0
      })

      this.meal.mealForm = hasSelectGoods

      // 如果是手动添加模式，不主动调用添加 （ 为了给推荐套餐页使用 ）
      if (!this.ifManualAdd) {
        this.$parent.addGoodsChange(this.meal.selectNumber, this.meal)
      } else {
        this.$emit('submit', this.meal.selectNumber, this.meal)
      }

      this.close()
    },

    /**
     * 判断用户是否满选了套餐配送
     * 1. 如果用户套餐配送未选满，提示用户让用户做选择
     * 2. 如果套餐配送商品为空，拒绝用户提交到购物车
     */
    computedIfFullSelect() {
      return new Promise((resolve, reject) => {
        const mealGroupFormGoods = this.mealFormGoods
        if (!mealGroupFormGoods && mealGroupFormGoods.length === 0) return resolve(false)

        // 遍历各组
        for (let i in mealGroupFormGoods) {
          let mealGroupForm = mealGroupFormGoods[i]
          let mealGroupFormStatistics = mealGroupForm.reduce(
            (pre, item) => {
              pre.sumSelectNumber += item.selectNumber

              if (item.selectNumber) {
                if (pre.minNumber === 0) {
                  pre.minNumber = item.number
                }
                pre.minNumber = item.number > pre.minNumber ? pre.minNumber : item.number
              }

              return pre
            },
            { minNumber: 0, sumSelectNumber: 0 }
          )

          console.log('mealGroupFormStatistics', mealGroupFormStatistics)

          const groupName = this.selectMealFormGroups[i] || `第${i + 1}组`
          const optionalNumber = this.$utils.mathSubtract(mealGroupFormStatistics.minNumber, mealGroupFormStatistics.sumSelectNumber)
          if (mealGroupFormStatistics.minNumber === 0) {
            uni.showModal({
              title: '温馨提示',
              content: `套装配送${groupName}中您还暂未选择配送商品，是否确认下单？`,
              success: res => {
                return resolve(res.confirm)
              }
            })
            break
          } else if (mealGroupFormStatistics.sumSelectNumber < mealGroupFormStatistics.minNumber) {
            uni.showModal({
              title: '温馨提示',
              content: `套装配送${groupName}中还可继续选择${optionalNumber}件配送商品，是否确认下单？`,
              success: res => {
                return resolve(res.confirm)
              }
            })
            break
          }

          // 只有最后一组都满足了，才算真正全选了
          if (Number(i) === mealGroupFormGoods.length - 1) {
            return resolve(true)
          }
        }
      })
    },

    // 分组商品内的数据修改 - value +
    goodsChange(rowData, selectNumber, goods, type) {
      selectNumber = Number(selectNumber)

      if (type === 'minus') {
        rowData.selectNumber = selectNumber
      }

      const result = goods.reduce(
        (pre, item) => {
          pre.sumSelectNumber += item.selectNumber

          if (item.selectNumber) {
            if (pre.minNumber === 0) {
              pre.minNumber = item.number
            }
            pre.minNumber = item.number > pre.minNumber ? pre.minNumber : item.number
          }

          return pre
        },
        { minNumber: 0, sumSelectNumber: 0 }
      )

      if (result.sumSelectNumber >= rowData.number && type === 'plus') {
        console.log('当前选择的总数已经大于等于该商品的最大可选数')
        this.$msg('text', '当前选择的总数已经大于等于该商品的最大可选数')
        return
      }

      if (result.minNumber === 0) {
        result.minNumber = rowData.number
      }

      if (result.sumSelectNumber >= result.minNumber) {
        console.log('已大于等于当前最大可选数量', result.sumSelectNumber, result.minNumber)
        this.$msg('text', '已大于等于当前最小的最大可选数量')
        return
      }

      if (type == 'plus') {
        // 加法后添加，用于控制一些不可以添加的情况
        rowData.selectNumber = selectNumber
      }
    },

    // 设置当前点击的配送商品为最大可选
    setMaxNumber(mealFormGood, goods) {
      goods.forEach(good => {
        good.selectNumber = 0
      })

      mealFormGood.selectNumber = mealFormGood.number
    },

    /* 模态框操作  start */
    handlePre() {
      this.currentSwiperIndex--
    },
    handleNext() {
      this.currentSwiperIndex++
    },
    handleSubmit() {
      this.addToCart()
    },
    swiperChange(e) {
      this.currentSwiperIndex = e.detail.current
    },

    open(param) {
      this.$refs.modal.open({ showClose: this.$format(param, 'showClose', true) })
      this.ifManualAdd = this.$format(param, 'ifManualAdd', false)
      this.init()
    },
    clickModal() {
      this.showClose && this.close()
    },
    close() {
      this.currentSwiperIndex = 0

      this.$emit('afterModalClose')
      this.$refs.modal.close()
    },
    afterModalClose() {
      this.currentSwiperIndex = 0
      this.$emit('mealFormModalClose')
    }
    /* 模态框操作 end */
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
$activeBg: #282e44;
$modalContainerHeight: 80vh;
$mealContainerHeight: 50px;
$buttonBoxHeight: 70px;
.modal-container {
  height: $modalContainerHeight;
  position: relative;
  padding: 0;
  .meal-container {
    padding: 15px;
    box-sizing: border-box;
    z-index: 1;
    background: #292f45;
    color: $color-primary-grey-text;
    // box-shadow: 0px 5px 30px #1b2035;
    height: $mealContainerHeight;
    @include is-flex(row, space-between, center, nowrap);
  }

  .goods-swiper {
    width: 100%;
    // background: $activeBg !important;
    height: calc(#{$modalContainerHeight} - #{$mealContainerHeight} - #{$buttonBoxHeight});
    // font-size: $font-size-xs;

    .goods-swiper-item {
      width: 100%;
      height: 100%;
      box-sizing: border-box;
      padding: 15px;
      .goods-container {
        width: 100%;
        height: 100%;
      }
      .swiper-title {
        padding-bottom: 10px;
        color: $color-primary-text;
        font-weight: bold;
        // font-size: $font-size-lg;
        // letter-spacing: 1px;
      }
      .goods-item {
        margin-bottom: 10px;
        padding-bottom: 10px;
        @include border-bottom;
        &:last-child {
          border-bottom: none;
        }
        .goods-name {
          color: $color-primary-grey-text;
        }
        .tags {
          display: flex;
          // font-size: $font-size-xs;
          font-size: 9px;
          margin: 6px 0 2px 0;
        }
      }
    }
  }

  .button-box {
    height: $buttonBoxHeight;
    padding: 15px;
    box-shadow: 10px -10px 10px $box-shadow;
    @include is-flex(row, space-between, center, nowrap);
    box-shadow: 0px 0px 4px 0px rgba(0, 0, 0, 0.4);

    .my-button {
      border-radius: 7px;
    }

    .pre-button {
      flex: 1;
      margin-right: 10px;
      background: linear-gradient(180deg, #464e69, #20273d);
      color: $gold;
    }
    .next-button {
      flex: 1;
      background-color: linear-gradient(180deg, #ffedcb, #f1c99a);
    }
    .submit-button {
      flex: 1;
    }
  }
}
</style>
